package com.jinpin.oauth.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jinpin.oauth.entity.LoginUser;
import com.jinpin.oauth.entity.Permission;
import com.jinpin.oauth.entity.Role;
import com.jinpin.oauth.entity.User;
import com.jinpin.oauth.mapper.PermissionMapper;
import com.jinpin.oauth.mapper.RoleMapper;
import com.jinpin.oauth.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;


    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.用户校验 从数据库查用户 ，存在则进行下一步，不存在就抛出异常
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
        if (BeanUtil.isEmpty(user)) {
            throw new UsernameNotFoundException("账号或密码错误");
        }
        // 2.查询角色与权限
        Role role = roleMapper.getRoleByUid(user.getId());
        List<Permission> permissions = permissionMapper.getListByRid(role.getRoleId());
        List<String> collect = new ArrayList<>();
//        List<String> collect = permissions.stream().map(Permission::getPermission).collect(Collectors.toList());
        collect.add(role.getRoleStr());
        return new LoginUser(user,collect);
    }


}
